package com.hdu.clj.fitness

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_talk.*
import kotlinx.android.synthetic.main.talk_title.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.concurrent.schedule

class talkActivity : AppCompatActivity(),View.OnClickListener {


    private val msgList = ArrayList<Msg>()

    private var adapter:MsgAdapter?=null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_talk)
        initMsg()
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        adapter = MsgAdapter(msgList)
        recyclerView.adapter =adapter
        send.setOnClickListener(this)
        talkTitleText.setText("机器人")
    }

    override fun onClick(v: View?) {
        val dbTalkHelper = talkDatabase(this,"Talk.db",1)
        val dbTalk = dbTalkHelper.writableDatabase
        when(v){
            send ->{
                val content = inputText.text.toString()
                if (content.isNotEmpty()){
                    talkTitleText.setText("对方正在输入...")
                    dbTalk.execSQL("insert into Talk(content) values(?)", arrayOf(content))
                    val msg = Msg(content,Msg.TYPE_SENT)
                    msgList.add(msg)
                    adapter?.notifyItemInserted(msgList.size-1)
                    recyclerView.scrollToPosition(msgList.size-1)
                    inputText.setText("")
                    Handler().postDelayed({
                        val ans = Msg(Answer().answer(content,this),Msg.TYPE_RECEIVED)
                        msgList.add(ans)
                        adapter?.notifyItemInserted(msgList.size - 1)
                        recyclerView.scrollToPosition(msgList.size-1)
                        talkTitleText.setText("机器人")
                    },800)
//                    val ans = Msg(Answer().answer(content),Msg.TYPE_RECEIVED)
//                    msgList.add(ans)
//                    adapter?.notifyItemInserted(msgList.size - 1)
                }
            }
        }
    }

    private fun initMsg() {
        val msg1 = Msg("你好呀！",Msg.TYPE_RECEIVED)
        msgList.add(msg1)
    }
}
